package com0oky.httpkit.http.request;

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 请求工具类
 * @author mdc
 * @date 2017年6月11日
 */
public class RequestKit {
	
	private static Logger logger = LoggerFactory.getLogger(RequestBase.class);
	
	/**
	 * 关闭OutputStream,忽略异常
	 * @author mdc
	 * @date 2017年6月11日
	 * @param closeable
	 */
	public static void closeQuietly(OutputStream closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }
	
	/**
	 * 关闭InputStream,忽略异常
	 * @author mdc
	 * @date 2017年6月11日
	 * @param closeable
	 */
	public static void closeQuietly(InputStream closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}
	
	public static void closeQuietly(ImageInputStream closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}
	
	public static void closeQuietly(ImageOutputStream closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}
	
	public static void closeQuietly(HttpResponse closeable) {
		try {
			if (closeable != null && closeable instanceof CloseableHttpResponse) {
				((CloseableHttpResponse)closeable).close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}
	
	public static void closeQuietly(CloseableHttpClient closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}
	
	
	
	
	/**
	 * 获取LayeredConnectionSocketFactory 使用ssl单向认证
	 * @author mdc
	 * @date 2015年7月17日
	 * @return
	 */
	public static LayeredConnectionSocketFactory getSSLSocketFactory() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();

			return new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	

	/**
	 * 把Map参数转换为List
	 * @author mdc
	 * @date 2016年5月12日
	 * @param parameters
	 * @return
	 */
	public static List<NameValuePair> convertNameValuePair(final Map<String, ?> parameters) {
		List<NameValuePair> values = new ArrayList<NameValuePair>(parameters.size());
		
		String value = null;
		for (Entry<String, ?> parameter : parameters.entrySet()) {
			value = parameter.getValue() == null? null : parameter.getValue().toString();
			values.add(new BasicNameValuePair(parameter.getKey(), value));
		}
		return values;
	}
	
	/**
	 * 根据最大次数重试
	 */
	public static HttpRequestRetryHandler TIMES_RETRY_HANDLER = new HttpRequestRetryHandler() { 
		public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
			System.out.println(executionCount);
			
			if (executionCount >= 5) {
				// 如果超过最大重试次数，不重试
				return false;
			}
			
			if (exception instanceof InterruptedIOException) {
				// 超时
				return false;
			}
			
			if (exception instanceof UnknownHostException) {
				return false;
			}
			
			if (exception instanceof ConnectTimeoutException) {
				// 连接被拒绝
				return false;
			}
			
			if (exception instanceof SSLException) {
				// SSL握手异常
				return false;
			}
			
			 HttpClientContext clientContext = HttpClientContext.adapt(context);  
	         HttpRequest request = clientContext.getRequest();  
	         boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
	         
	         if (idempotent) {  
	             // 如果请求被认为是等幂，则重试
	             return true;  
	         }  
	         
	         return false;  
		};
	};
	
	
}
